<template>
  <div class="preview-content">
    <el-skeleton v-if="loading" :rows="10" animated />
    <div v-else-if="error" class="error-message">
      <el-alert :title="error" type="error" />
    </div>
    <div v-else class="content">
      <img
        v-if="file.file_type === 'image'"
        :src="`data:image/png;base64,${previewData?.preview_data}`"
        class="preview-image"
      />
      <pre
        v-else-if="file.file_type === 'text'"
        class="preview-text"
      >{{ previewData?.preview_data }}</pre>
      <div v-else class="unsupported-type">
        <el-empty description="暂不支持该文件类型的预览" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FileInfo } from '@/types/file'

const props = defineProps<{
  file: FileInfo
}>()

const loading = ref(false)
const error = ref<string | null>(null)
const previewData = ref<any>(null)

const fetchPreview = async () => {
  loading.value = true
  error.value = null
  try {
    const response = await fetch(`/api/preview?file_path=${encodeURIComponent(props.file.file_path)}`)
    const data = await response.json()
    if (data.status === 'success') {
      previewData.value = data.data
    } else {
      error.value = data.message || '获取预览失败'
    }
  } catch (err) {
    error.value = '获取预览失败'
  } finally {
    loading.value = false
  }
}

watch(() => props.file, () => {
  fetchPreview()
})

onMounted(() => {
  fetchPreview()
})
</script>

<style lang="scss" scoped>
.preview-content {
  height: 100%;
  padding: 20px;

  .content {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: flex-start;
  }

  .preview-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }

  .preview-text {
    width: 100%;
    padding: 16px;
    background: var(--el-fill-color-light);
    border-radius: 4px;
    font-family: monospace;
    white-space: pre-wrap;
    word-break: break-all;
  }

  .unsupported-type {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style> 